package com.debt.oauth.test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.Map;

/**
 * @author GaoZeXi
 */
public class ApplyToken {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();

        //构造请求地址,http://localhost:9200/oauth/token
        String url ="http://localhost:9200/oauth/token";
        //构造请求体 body ,headers
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("grant_type","authorization_code");
        body.add("code","authorization_code");
        body.add("redirect_uri","http://localhost");
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<>(body);

        //当后端出现了401,400后端不对这两个异常编码进行处理,而是直接返回前端
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if(response.getRawStatusCode()!=400&&response.getRawStatusCode()!=401){
                    super.handleError(response);
                }
            }
        });

        //发送请求
        ResponseEntity<Map> respEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
        Map map = respEntity.getBody();
        System.out.println("map = " + map);
    }
}
